import Vue from 'vue'
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import { ACCESS_TOKEN, ALL_APPS_MENU, LOGIN_SYS } from '@/store/mutation-types'
// import { SSOLogin } from './api/modular/system/QhseToken'

import { Modal, notification } from 'ant-design-vue' // NProgress Configuration
import { getDepartmentEarlyWarningInfo } from '@/api/modular/system/QHSEWarning'
// import { QHSEgetUserInfo } from '@/api/modular/system/QHSEloginManage'
import { QHSELogin } from '@/api/modular/system/QhseToken'
/// es/notification
const whiteList = ['login', 'register', 'registerResult'] // no redirect whitelist
// 无默认首页的情况
const defaultRoutePath = '/analysis'
Vue.ls.remove(ACCESS_TOKEN)
Vue.ls.remove(ALL_APPS_MENU)
// console.log('Query params:', router)
router.beforeEach((to, from, next) => {
  // console.log('Query params:', to.query)
  const id = to.query.id
  if (id) {
    console.log('idpath', id)
    Vue.ls.set('id', id)
  }
  const currentUrl = new URL(window.location.href)
  // console.log(currentUrl)
  var token = currentUrl.searchParams.get('token')
  currentUrl.searchParams.append('lang', 'zh')
  var lang = currentUrl.searchParams.get('lang') || 'zh'
  store.commit('setLang', lang)
  if (token) {
    currentUrl.searchParams.delete('token')
    window.history.replaceState({}, '', currentUrl.toString())
    Vue.ls.set('token', token, 7 * 24 * 60 * 60 * 1000)
  }
  NProgress.start() // start progress bar
  // console.log('to.path:' + to.path)
  // console.log(document.referrer)
  to.meta && typeof to.meta.title !== 'undefined' && setDocumentTitle(`${to.meta.title} - ${domTitle}`)
  if (Vue.ls.get(ACCESS_TOKEN)) {
    /* has token */
    if (to.path === '/user/login') {
      // console.log('zheliya1')
      next({ path: defaultRoutePath })
      NProgress.done()
    } else {
      // if (!token) {
      //   const url = process.env.VUE_APP_API_BASE_URL + '/SSO/SSO'
      //   console.log('url', url)
      //   fetch(url, { mode: 'no-cors' })
      // }
      // console.log('zheliya2')
      if (!token && Vue.ls.get(LOGIN_SYS) === 2) {
        // console.log('没有token走这里')
        if (store.getters.roles.length === 0) {
          store
            .dispatch('GetInfo')
            .then(res => {
              // console.log('res', res)
              if (res.menus.length < 1) {
                Modal.error({
                  title: '提示：',
                  content: '无菜单权限，请联系管理员',
                  okText: '确定',
                  onOk: () => {
                    store.dispatch('Logout').then(() => {
                      window.location.reload()
                    })
                  }
                })
                return
              }
              // eslint-disable-next-line camelcase
              const all_app_menu = Vue.ls.get(ALL_APPS_MENU)
              let antDesignmenus
              // eslint-disable-next-line camelcase
              if (all_app_menu == null) {
                const applocation = []
                res.apps.forEach(item => {
                  const apps = { code: '', name: '', active: '', menu: '' }
                  const menus = res.menus.filter(m => m.application === item.code)
                  if (item.active) {
                    apps.code = item.code
                    apps.name = item.name
                    apps.active = item.active
                    apps.menu = menus
                    antDesignmenus = menus
                  } else {
                    apps.code = item.code
                    apps.name = item.name
                    apps.active = item.active
                    apps.menu = menus
                  }
                  applocation.push(apps)
                })
                Vue.ls.set(ALL_APPS_MENU, applocation, 7 * 24 * 60 * 60 * 1000)
                // // 延迟 1 秒显示欢迎信息
                // setTimeout(() => {
                //   notification.success({
                //     message: '欢迎',
                //     description: `${timeFix()}，欢迎回来`
                //   })
                // }, 1000)
              } else {
                antDesignmenus = Vue.ls.get(ALL_APPS_MENU)[0].menu
              }
              store.dispatch('GenerateRoutes', { antDesignmenus }).then(() => {
                // 动态添加可访问路由表
                router.addRoutes(store.getters.addRouters)
                // 请求带有 redirect 重定向时，登录自动重定向到该地址
                const redirect = decodeURIComponent(from.query.redirect || to.path)
                if (to.path === redirect) {
                  next({ path: redirect })
                  // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                  next({ ...to, replace: true })
                } else {
                  // 跳转到目的路由
                  next({ path: redirect })
                }
              })
            })
            .catch(() => {
              store.dispatch('Logout').then(() => {
                next({ path: '/user/login', query: { redirect: to.fullPath } })
              })
            })
        } else {
          next()
        }
      } else {
        // console.log('有token走这里')
        if (store.getters.roles.length === 0) {
          store
            .dispatch('QHSEgetUserInfo')
            .then(res => {
              // console.log('QHSEgetUserInfo返回的数据', res)
              if (res.menus.length < 1) {
                Modal.error({
                  title: '提示：',
                  content: '无菜单权限，请联系管理员',
                  okText: '确定',
                  onOk: () => {
                    store.dispatch('Logout').then(() => {
                      window.location.reload()
                    })
                  }
                })
                return
              }
              // eslint-disable-next-line camelcase
              const all_app_menu = Vue.ls.get(ALL_APPS_MENU)
              let antDesignmenus
              // eslint-disable-next-line camelcase
              if (all_app_menu == null) {
                const applocation = []
                res.apps.forEach(item => {
                  const apps = { code: '', name: '', active: '', menu: '' }
                  const menus = res.menus.filter(m => m.application === item.code)
                  if (item.active) {
                    apps.code = item.code
                    apps.name = item.name
                    apps.active = item.active
                    apps.menu = menus
                    antDesignmenus = menus
                  } else {
                    apps.code = item.code
                    apps.name = item.name
                    apps.active = item.active
                    apps.menu = menus
                  }
                  applocation.push(apps)
                })
                Vue.ls.set(ALL_APPS_MENU, applocation, 7 * 24 * 60 * 60 * 1000)
                console.log('登录成功')
                // console.log(Vue.ls.get(ALL_APPS_MENU))
                // 调用接口查询人员预警信息
                let notificationKey1 = null
                let notificationKey2 = null
                let notificationKey3 = null
                const param = { id: '' }
                param.id = res.secondOrganizationId
                // console.log('param', param)
                getDepartmentEarlyWarningInfo(Object.assign(param)).then(res => {
                  if (!res.success) {
                    return
                  }
                  // console.log(param, 'param查询条件')
                  // console.log(res.data, '最新查询数据')
                  const departmentCount1 = res.data.warningDepartments
                  const departmentCount2 = res.data.warningViolationDepartments
                  const personCount = res.data.warningPersonnel
                  const warningScore = res.data.score
                  // console.log('res.data', res.data)
                  // 显示单位预警信息并实现跳转
                  if (departmentCount1 > 0) {
                    notification.warn({
                      message: '单位隐患预警',
                      key: 'warning1',
                      description: res.data.organizationName + `共有` + departmentCount1 + `单位满足停产条件`,
                      onClick: key => {
                        // 存储通知框的key
                        notificationKey1 = key
                        // 在点击通知时触发的事件中进行页面跳转
                        next({
                          path: '/unitDangerWarning',
                          query: {
                            organizationName: res.data.organizationName,
                            timeOn: res.data.timeOn,
                            timeEnd: res.data.timeEnd,
                            organizationId: res.data.organizationId
                          }
                        })
                        // 关闭警示框
                        if (notificationKey1 !== null) {
                          notification.close(notificationKey1)
                        }
                      },
                      duration: 10
                    })
                    // console.log(1)
                  }
                  // 显示单位违章信息并实现跳转
                  if (departmentCount2 > 0) {
                    setTimeout(() => {
                      notification.warn({
                        message: '单位违章预警',
                        key: 'warning2',
                        description: res.data.organizationName + `共有` + departmentCount2 + `单位满足停工条件`,
                        onClick: key => {
                          // 存储通知框的key
                          notificationKey2 = key
                          // 在点击通知时触发的事件中进行页面跳转
                          next({
                            path: '/unitViolationWarning',
                            query: {
                              organizationName: res.data.organizationName,
                              timeOn: res.data.timeOn,
                              timeEnd: res.data.timeEnd,
                              organizationId: res.data.organizationId
                            }
                          })
                          // 关闭警示框
                          if (notificationKey2 !== null) {
                            notification.close(notificationKey2)
                          }
                        },
                        duration: 10
                      })
                    }, 110)
                    // console.log(2)
                  }
                  if (personCount > 0) {
                    setTimeout(() => {
                      // 显示人员预警信息并实现跳转
                      notification.warn({
                        message: '人员预警',
                        key: 'warning3',
                        description:
                          res.data.organizationName + `共有` + personCount + `人员计分达到` + warningScore + `分预警`,
                        onClick: key => {
                          // 存储通知框的key
                          notificationKey3 = key
                          // 在点击通知时触发的事件中进行页面跳转
                          next({
                            path: '/peopleWarning',
                            query: {
                              organizationName: res.data.organizationName,
                              timeOn: res.data.timeOn,
                              timeEnd: res.data.timeEnd,
                              score: res.data.score,
                              organizationId: res.data.organizationId
                            }
                          })
                          // 关闭警示框
                          if (notificationKey3 !== null) {
                            notification.close(notificationKey3)
                          }
                        },
                        duration: 10
                      })
                    }, 100)
                  }
                })
              } else {
                antDesignmenus = Vue.ls.get(ALL_APPS_MENU)[0].menu
              }
              store.dispatch('GenerateRoutes', { antDesignmenus }).then(() => {
                router.addRoutes(store.getters.addRouters)
                // 请求带有 redirect 重定向时，登录自动重定向到该地址
                const redirect = decodeURIComponent(from.query.redirect || to.path)
                if (to.path === redirect) {
                  next({ path: redirect })
                  // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                  next({ path: redirect, replace: true })
                } else {
                  next({ path: '/user/login' })
                }
              })
            })
            .catch(() => {
              store.dispatch('Logout').then(() => {
                next({ path: '/user/login', query: { redirect: to.fullPath } })
              })
            })
        } else {
          next()
        }
      }
    }
  } else {
    if (whiteList.includes(to.name)) {
      // console.log('zheliya3')
      // 在免登录白名单，直接进入
      next()
    } else {
      // console.log('to.fullPath:', to.fullPath)
      if (to.path === '/user/login') {
        // console.log('本地部署')
        next({ path: '/user/login', query: { redirect: to.fullPath } })
      } else {
        // if (token) {
        //   token = '822d0b5a2bab40f3a71943fec4995dc7'
        // }
        // console.log(process.env.VUE_APP_API_BASE_URL)
        const url = process.env.VUE_APP_API_BASE_URL + '/SSO/TestLogin'
        // console.log(url)
        // 创建一个包含token参数的URL
        token = Vue.ls.get('token')
        lang = Vue.ls.get('lang')
        const urlWithToken = `${url}?token=${token}`
        if (urlWithToken) {
          // 发起GET请求
          fetch(urlWithToken)
            .then(response => {
              // console.log('response', response)
              if (response.ok) {
                return response.json()
              } else {
                throw new Error('请求失败')
              }
            })
            .then(data => {
              // console.log('响应数据:', data)
              if (data.code === 200 && data.result !== null) {
                QHSELogin(data.result).then(res => {
                  // console.log('loginRes1111:', res)
                  const accessToken = res.data
                  Vue.ls.set(ACCESS_TOKEN, accessToken, 7 * 24 * 60 * 60 * 1000)
                  Vue.ls.set(LOGIN_SYS, 1, 7 * 24 * 60 * 60 * 1000)
                  store.commit('SET_TOKEN', accessToken)
                  // if (id && type && redirctUrl) {
                  //   console.log('走的是SSO的')
                  //   next({ path: `/${redirctUrl}`, replace: true })
                  // } else if (!id && !type && !redirctUrl) {
                  //   console.log('走的是普通的')
                  next({ ...to, replace: true })
                  // }
                })
              } else {
                // console.log('获取数据失败！')
                // Vue.prototype.$message.warning('获取数据失败')
                next({ path: '/user/login', query: { redirect: to.fullPath } })
              }
            })
            .catch(error => {
              console.error('发生错误:', error)
            })
        } else {
          // 获取失败
          // console.log('获取token为空！')
          // Vue.prototype.$message.warning('获取code为空, 输入账号登陆!')
          next({ path: '/user/login', query: { redirect: to.fullPath } })
        }
      }
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
  // NProgress.configure({ showSpinner: false })
})
